package com.liang.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.liang.gateway.entity.AuthPermission;
import com.liang.gateway.entity.AuthRole;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 自定义权限验证接口扩展
 */
@Component
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {

    private final RedisTemplate<String, Object> redisTemplate;

    private String authPermissionPrefix = "auth:permission:";
    private String authRolePrefix = "auth:role:";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        String key = authPermissionPrefix + loginId;
        String authStr = (String) redisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(authStr)) {
            return Collections.emptyList();
        }
        List<AuthPermission> authPermissionList = JSONUtil.toList(authStr, AuthPermission.class);
        return authPermissionList.stream()
                .map(AuthPermission::getPermissionKey)
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        List<String> list = new ArrayList<>();
        String key = authRolePrefix + loginId;
        String roleStr = (String) redisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(roleStr)) {
            return Collections.emptyList();
        }
        List<AuthRole> roleList = JSONUtil.toList(roleStr, AuthRole.class);
        return roleList.stream()
                .map(AuthRole::getRoleKey)
                .collect(Collectors.toList());
    }
}
